package com.skt.common_hr.common.approval
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.memberselector.MemberSelectorProxy;
	import com.wcl.utils.StringUtil;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;

	public class AppLineMediator extends Mediator
	{
		public static const NAME:String = "AppLineMediator";
		public static const CLOSED_APPROVAL_LINE_VIEW:String = "closedAppLineView";
		public static const CANCEL_APPROVAL_LINE_VIEW:String = "cancelAppLineView";
		
		private var bWaitingDelegator:Boolean = false;
			
		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
		public function AppLineMediator()
        {
            super( NAME, null );
        }
		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
		protected function initView():void 
 		{
 			setEventListener();
 		}

		private function setEventListener():void
		{
			view.addEventListener(AppLineView.OK_VIEW, onOkView);
			view.addEventListener(AppLineView.CANCEL_VIEW, onCancelView);
			view.addEventListener(AppLineEvent.SELECTED_ORG, onSelectedOrg);
		}

		private function registerProxies():void
		{
			var proxy:MemberSelectorProxy = facade.retrieveProxy(MemberSelectorProxy.NAME) as MemberSelectorProxy;
			if(proxy == null) {
				proxy = new MemberSelectorProxy();
				facade.registerProxy(proxy);
			}
		}

		private function loadOrgList():void
		{
			var proxy:MemberSelectorProxy = facade.retrieveProxy(MemberSelectorProxy.NAME) as MemberSelectorProxy;
			proxy.loadOrg(Variables.myPernr, "");
		}
		
		private function loadMemberList(orgCode:String):void
		{
			var proxy:MemberSelectorProxy = facade.retrieveProxy(MemberSelectorProxy.NAME) as MemberSelectorProxy;
			proxy.loadMember(orgCode);
		}


		public function execView(parent:DisplayObject, lineList:ArrayCollection):void
		{
            registerProxies();
            loadOrgList();
			if(view==null) {
				createPopUp(parent);
				view.initView();
				view.callLater(setEventListener);
			}	
			else {
				PopUpManager.addPopUp(view, parent.root,true);
			}		
			view.lineList = lineList;
			view.callLater(view.selectLineApprover);
		}
		
		public function get resultList():ArrayCollection
		{
			return view.lineList;
		}
		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
				MemberSelectorProxy.LOAD_MEMBERLIST_COMPLETE,
				MemberSelectorProxy.LOAD_MEMBERLIST_FAILED,
				MemberSelectorProxy.LOAD_ORGLIST_COMPLETE,
				MemberSelectorProxy.LOAD_ORGLIST_FAILED
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName()) 
			{
				case MemberSelectorProxy.LOAD_MEMBERLIST_COMPLETE:
					view.memberList = filteringMember(MemberSelectorProxy(note.getBody()).memberList);
					//view.memberList = MemberSelectorProxy(note.getBody()).memberList;
					break;
				case MemberSelectorProxy.LOAD_ORGLIST_COMPLETE:
					view.orgList = MemberSelectorProxy(note.getBody()).orgList;
					loadMemberList(Variables.myOrgCode);		//접속자의 소속분원 조회
					view.callLater(view.userDeptfind,[Variables.myOrgCode]);	//접속자의 소속분원  트리 열기
					//view.MemberSort();							//섬세한검색 소팅 실행
					break;
				case MemberSelectorProxy.LOAD_SEARCH_COMPLETE:
					view.memberList = MemberSelectorProxy(note.getBody()).memberList;
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}



		private function createPopUp(parent:DisplayObject):void
		{
			viewComponent = PopUpManager.createPopUp(parent.root, AppLineView, true);
			PopUpManager.centerPopUp(view);
			view.setFocus();
		}
		
		
		
		private function onOkView(e:Event):void
		{
			if(validateLine()) {
				view.closeView();
				facade.sendNotification(CLOSED_APPROVAL_LINE_VIEW, this);
			}
			else {
				CommonAlert.showMessage("CommonHr", "결재선이 올바르지 않습니다. 결재선을 정확하게 입력하십시오");
			}
		}

		private function onCancelView(e:Event):void
		{
			view.closeView();
			facade.sendNotification(CANCEL_APPROVAL_LINE_VIEW, this);
		}
		
		
		private function onSelectedMember(e:AppLineEvent):void
		{
		}

		private function onSelectedOrg(e:AppLineEvent):void
		{
			loadMemberList(e.orgCode);
		}
		
		private function validateLine():Boolean
		{
			var bAssinged:Boolean = true;
			for(var i:uint=0;i<view.lineList.length; i++) {
				var vo:ApprovalLineVO = view.lineList.getItemAt(i) as ApprovalLineVO;
				switch(i) {
					case 0:
						//if(findSameMember(i, vo.WPERNR)) return false;
						break;
					case 1:
						if(StringUtil.NVL(vo.WPERNR) == "")	bAssinged = false;
						else if(findSameMember(i, vo.WPERNR)) return false;
						break; 
					case 2: case 3:
						if(StringUtil.NVL(vo.WPERNR) != "") {
							if(!bAssinged) return false;
						}
						else bAssinged = false;
						break;
					case 4:
						if(StringUtil.NVL(vo.WPERNR) == "") return false;
						break;
				}
			}
			return true;	
		}

		private function findSameMember(startOf:uint, pernr:String):Boolean
		{
			for(var i:uint=startOf+1; i<view.lineList.length; i++) {
				if(pernr == (view.lineList.getItemAt(i) as ApprovalLineVO).WPERNR) {
					return true;
				}
			}
			return false;
		}
		
		private function filteringMember(src:ArrayCollection):ArrayCollection {
			// 직책이 없는 경우 본인을 선택할 수 없게 본인 레코드를 삭제
			if(Variables.myPosition == "") {
				for(var i:int=0; i<src.length; i++) {
					if(Variables.myPernr == src.getItemAt(i).PERNR) {
						src.removeItemAt(i);
						return src;
					}
				}
			}
			return src;
		}
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():AppLineView
        {
            return viewComponent as AppLineView;
        }
	}
}